package com.jyl.spzx.cloud.order.service.impl;

import com.jyl.spzx.cloud.order.bean.Order;
import com.jyl.spzx.cloud.order.bean.User;
import com.jyl.spzx.cloud.order.mapper.OrderMapper;
import com.jyl.spzx.cloud.order.service.OrderService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Random;

/**
 * @ClassName OrderServiceImpl
 * @Author admin
 * @Date 2024/7/1
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class OrderServiceImpl implements OrderService {

    private final OrderMapper orderMapper;

    private final RestTemplate restTemplate;

    private final DiscoveryClient discoveryClient;   // 服务发现客户端对象 -- 来自于SpringCloud

    /*
        version 3.0
        LoadBalanced 负载均衡
        用注册中心中服务提供方的服务名代替 ip地址 和 端口号
     */
    @Override
    public Order findOrderByOrderId(Long orderId) {
        Order order = orderMapper.getOrderById(orderId);
        String applicationName = "spzx-cloud-user";
        User forUser = restTemplate.getForObject("http://"+applicationName+"/api/user/findUserByUserId/" + order.getUserId(), User.class);
        order.setUser(forUser);
        return order;
    }

    /*
    version 2.0  discoveryClient
     */
/*
    @Override
    public Order findOrderByOrderId(Long orderId) {
        Order order = orderMapper.getOrderById(orderId);
        // 根据服务名称从注册中心中获取服务实例列表
        ServiceInstance serviceInstance = chooseServiceInstance("spzx-cloud-user");
        User forUser = restTemplate.getForObject("http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort() + "/api/user/findUserByUserId/" + order.getUserId(), User.class);
        order.setUser(forUser);
        log.info("{}",order);
        return order;
    }*/

    /**
     * 根据服务的名称从注册中心中获取服务地址信息
     */
    public ServiceInstance chooseServiceInstance(String applicationName) {
        List<ServiceInstance> instances = discoveryClient.getInstances(applicationName);
        int size = instances.size();
        Random random = new Random();
        int instanceIndex = random.nextInt(size);  // 入参 bound(界限,边界): 方法返回一个从0到size的随机数
        ServiceInstance serviceInstance = instances.get(instanceIndex);
        return serviceInstance;
    }

/*
    @Override
    public Order findOrderByOrderId(Long orderId) {
        Order order = orderMapper.getOrderById(orderId);
        // 发起远程调用
        User forUser = restTemplate.getForObject("http://localhost:10100/api/user/findUserByUserId/" + order.getUserId(), User.class);
        order.setUser(forUser);
        return order;
    }*/


}
